"""
主题: 启动与停止线程
问题: 你要为需要并发执行的代码创建/销毁线程
提示 : 
"""

import time
from threading import Thread
import socket

def countdown(n):
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(2)

class CountdownTask:
    '''退出标志'''
    def __init__(self):
        self._running = True

    def terminate(self):
        self._running = False

    def run(self, n):
        while self._running and n > 0:
            print('T-minus', n)
            n -= 1
            time.sleep(2) 

class IOTask:
    '''利用超时循环来小心操作线程'''
    def terminate(self):
        self._running = False

    def run(self, sock):
        # sock is a socket
        sock.settimeout(5)        # Set timeout period
        while self._running:
            # Perform a blocking I/O operation w/ timeout
            try:
                data = sock.recv(8192)
            except socket.timeout:
                continue
            # Continued processing
            print(data)

class CountdownThread(Thread):
    '''继承'''
    def __init__(self, n):
        super().__init__()
        self.n = n
    def run(self):
        while self.n > 0:

            print('T-minus', self.n)
            self.n -= 1
            time.sleep(2)

def recipe1():
    t = Thread(target=countdown, args=(10,))
    t.start()

    if t.is_alive():
        print('Still running')
    else:
        print('Completed')

    t.join()  

def recipe2():
    from threading import Thread

    c = CountdownTask()
    t = Thread(target=c.run, args=(10,))
    t.start()
    time.sleep(3)

    c.terminate() # Signal termination
    t.join()      # Wait for actual termination (if needed)


def recipe3():
    import multiprocessing
    c = CountdownTask()
    p = multiprocessing.Process(target=c.run, args=(10,))
    p.start()
    time.sleep(5)
    # 注意：无法终止
    #c.terminate() # Signal termination
    p.terminate()
    p.join()      # Wait for actual termination (if needed)

def recipe4():
    c = CountdownThread(5)
    c.start()  
    c.join()

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()


if __name__ == '__main__':
    main()           